import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Post } from '../adminPost/entity/post.entity';
import { Cover } from '../adminPost/entity/cover.entity';

@Injectable()
export class AppWebService {
  constructor(
    @InjectRepository(Post) private readonly postRepository: Repository<Post>,
    @InjectRepository(Cover)
    private readonly coverRepository: Repository<Cover>,
  ) {}

  // 查询帖子列表
  async queryPostListByPage(pageSize: number, pageIndex: number) {
    let postCount = 0;
    let queryByAny = `select * from post order by updateTime desc limit ${pageIndex *
      pageSize},${pageSize}`;
    const pageData = await this.postRepository.query(queryByAny);
    [, postCount] = await this.postRepository.findAndCount();

    for (let item of pageData) {
      let queryImgByPostId = `select a.coverImg from cover a where postId = '${item['postId']}'`;
      let mapResult = await this.coverRepository.query(queryImgByPostId);
      item.coverImg = [];
      mapResult &&
        mapResult.forEach(element => {
          item.coverImg.push(element.coverImg);
        });
    }

    typeof postCount === 'number'
      ? ''
      : (postCount = parseInt(postCount[0]['count(1)']));

    return {
      msg: '查询成功',
      data: {
        pageData,
        total: postCount,
      },
    };
  }

  // 查询帖子详情
  async queryPostDetailById(postId: string) {
    let queryPostByPostId = `select * from post where postId = '${postId}'`;
    let result = await this.postRepository.query(queryPostByPostId);
    return {
      msg: '查询成功',
      data: result[0],
    };
  }
}
